class AuthorizationPanel {
    constructor(homeApp) {
        this.app = homeApp;
        this.currentAuthorization = null;
        this.stages = []; // 存储阶段数据
    }

    initAuthorizationPanel() {
        // 初始化添加授权按钮
        const addAuthorizationBtn = document.getElementById('add-authorization-btn');
        if (addAuthorizationBtn) {
            addAuthorizationBtn.addEventListener('click', () => {
                this.showAuthorizationModal('add');
            });
        }

        // 初始化搜索框
        const searchInput = document.querySelector('#authorizations-panel .search-input');
        if (searchInput) {
            searchInput.addEventListener('input', (e) => {
                // 实现搜索功能
                this.searchAuthorizations(e.target.value);
            });
        }
    }

    async loadAuthorizations() {
        try {
            const response = await this.app.authenticatedFetch('/api/web/authorization/getAll');
            const result = await response.json();
            
            if (result.code === 200) {
                const authorizations = result.data || [];
                this.renderAuthorizations(authorizations);
            } else {
                console.error('获取授权数据失败:', result.message);
                this.renderAuthorizations([]);
            }
        } catch (error) {
            console.error('加载授权数据失败:', error);
            this.renderAuthorizations([]);
        }
    }
    
    formatDate(dateString) {
        if (!dateString) return '';
        
        // 解析日期字符串
        const date = new Date(dateString);
        
        // 格式化为 yyyy/mm/dd
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1
        const day = String(date.getDate()).padStart(2, '0');
        
        return `${year}/${month}/${day}`;
    }

    renderAuthorizations(authorizations) {
        const tbody = document.getElementById('authorizations-table-body');
        if (!tbody) return;

        if (!authorizations || authorizations.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8">暂无授权数据</td></tr>';
            return;
        }

        tbody.innerHTML = authorizations.map(auth => `
            <tr>
                <td>${auth.id}</td>
                <td>${auth.userNickname || '未知用户(' + auth.userId + ')'}</td>
                <td>${auth.stageTitle || '未知阶段(' + auth.stageId + ')'}</td>
                <td>${this.formatDate(auth.startTime) || ''}</td>
                <td>${this.formatDate(auth.endTime) || ''}</td>
                <td>${this.formatDate(auth.createTime) || ''}</td>
                <td>${this.formatDate(auth.updateTime) || ''}</td>
                <td>
                    <button class="btn small" onclick="homeApp.authorizationPanel.editAuthorization(${auth.id})">编辑</button>
                    <button class="btn small danger" onclick="homeApp.authorizationPanel.deleteAuthorization(${auth.id})">删除</button>
                </td>
            </tr>
        `).join('');
    }

    // 通用的模态框初始化方法
    async initAuthorizationModal(mode, authorization = null) {
        // 获取阶段数据
        await this.loadStages();
        
        // 加载外部模态框模板
        try {
            const response = await fetch('/templates/authorization-modal.html');
            const template = await response.text();
            
            // 创建模态框
            const modal = document.createElement('div');
            modal.className = 'modal';
            modal.id = 'authorization-modal';
            modal.innerHTML = template;
            
            // 添加到页面
            document.body.appendChild(modal);
            
            // 设置标题和按钮文本
            const titleElement = modal.querySelector('h3');
            const submitButton = modal.querySelector('.btn.primary');
            if (mode === 'add') {
                titleElement.textContent = '添加授权';
                submitButton.textContent = '添加授权';
            } else {
                titleElement.textContent = '编辑授权';
                submitButton.textContent = '保存更改';
            }
            
            return modal;
        } catch (error) {
            console.error('加载模态框模板失败:', error);
            return null;
        }
    }

    // 通用的用户搜索功能
    setupUserSearch(phoneInput, suggestionsDiv, userTag, userIdInput) {
        phoneInput.addEventListener('input', async (e) => {
            const phone = e.target.value;
            if (phone.length >= 3) {
                const users = await this.searchUsersByPhone(phone);
                suggestionsDiv.innerHTML = users.map(user => `
                    <div class="suggestion-item" data-user-id="${user.id}" data-user-nickname="${user.nickname}" data-user-phone="${user.phone}">
                        ${user.phone} (${user.nickname})
                    </div>
                `).join('');
                suggestionsDiv.style.display = 'block';
            } else {
                suggestionsDiv.style.display = 'none';
            }
        });

        // 点击建议项选择用户
        suggestionsDiv.addEventListener('click', (e) => {
            if (e.target.classList.contains('suggestion-item')) {
                const userId = e.target.dataset.userId;
                const userNickname = e.target.dataset.userNickname;
                const userPhone = e.target.dataset.userPhone;

                // 清除输入框内容和建议列表
                phoneInput.value = '';
                suggestionsDiv.style.display = 'none';

                // 更新用户标签
                const userSpan = userTag.querySelector('span');
                if (userSpan) {
                    userSpan.textContent = `${userPhone} (${userNickname})`;
                }
                userTag.style.display = 'flex';

                // 隐藏输入框并移除required属性
                phoneInput.style.display = 'none';
                phoneInput.removeAttribute('required');

                // 设置隐藏的用户ID字段
                if (userIdInput) {
                    userIdInput.value = userId;
                }
            }
        });
    }

    // 通用的关闭按钮设置
    setupCloseButtons(modal, closeBtn, cancelBtn) {
        const closeModal = () => {
            if (modal && modal.parentNode) {
                // 重置表单中的手机号输入框
                const phoneInput = modal.querySelector('#phone');
                if (phoneInput) {
                    phoneInput.style.display = 'block';
                    phoneInput.setAttribute('required', 'required');
                }
                
                // 隐藏用户标签
                const userTag = modal.querySelector('.user-tag');
                if (userTag) {
                    userTag.style.display = 'none';
                }
                
                // 清空用户ID隐藏字段
                const userIdInput = modal.querySelector('#user-id');
                if (userIdInput) {
                    userIdInput.value = '';
                }
                
                modal.parentNode.removeChild(modal);
            }
        };

        if (closeBtn) {
            closeBtn.addEventListener('click', closeModal);
        }

        if (cancelBtn) {
            cancelBtn.addEventListener('click', closeModal);
        }

        // 点击模态框外部关闭
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                closeModal();
            }
        });
    }

    // 填充阶段选择选项
    populateStageOptions(stageSelect) {
        // 清空现有选项
        stageSelect.innerHTML = '<option value="">请选择阶段</option>';
        
        // 添加阶段选项
        this.stages.forEach(stage => {
            const option = document.createElement('option');
            option.value = stage.id;
            option.textContent = stage.title;
            stageSelect.appendChild(option);
        });
    }

    // 显示授权模态框 (用于添加和编辑)
    async showAuthorizationModal(mode, id = null) {
        let authorization = null;
        let user = {};

        // 如果是编辑模式，先获取要编辑的授权信息
        if (mode === 'edit') {
            try {
                const response = await this.app.authenticatedFetch('/api/web/authorization/getAll');
                const result = await response.json();

                if (result.code !== 200) {
                    alert('获取授权信息失败: ' + result.message);
                    return;
                }

                const authorizations = result.data || [];
                authorization = authorizations.find(auth => auth.id === id);

                if (!authorization) {
                    alert('未找到指定的授权信息');
                    return;
                }

                // 获取用户数据
                try {
                    const userResponse = await this.app.authenticatedFetch('/api/web/user/getAll');
                    const userResult = await userResponse.json();
                    if (userResult.code === 200) {
                        const users = userResult.data || [];
                        user = users.find(u => u.id === authorization.userId) || {};
                    }
                } catch (userError) {
                    console.warn('获取用户信息失败:', userError);
                }
            } catch (error) {
                console.error('加载授权信息失败:', error);
                alert('加载授权信息失败，请稍后重试');
                return;
            }
        }

        // 初始化模态框
        const modal = await this.initAuthorizationModal(mode, authorization);
        
        if (!modal) {
            console.error('无法加载模态框模板');
            alert('无法打开授权模态框，请稍后重试');
            return;
        }

        // 获取今天的日期
        const today = new Date();
        const todayStr = today.toISOString().split('T')[0];
        // 计算30天后的日期作为默认结束时间
        const defaultEndTime = new Date(today);
        defaultEndTime.setDate(today.getDate() + 30);
        const defaultEndTimeStr = defaultEndTime.toISOString().split('T')[0];



        // 获取元素
        const closeBtn = modal.querySelector('.close');
        const cancelBtn = modal.querySelector('#cancel-authorization');
        const form = modal.querySelector('#authorization-form');
        const phoneInput = modal.querySelector('#phone');
        const suggestionsDiv = modal.querySelector('#user-suggestions');
        const userTag = modal.querySelector('.user-tag');
        const userIdInput = modal.querySelector('#user-id');

        // 填充表单数据 (编辑模式)
        if (mode === 'edit' && authorization) {
            // 填充表单数据
            const form = modal.querySelector('#authorization-form');
            form.querySelector('#auth-id').value = authorization.id;

            // 填充用户信息
            const userTag = modal.querySelector('.user-tag');
            const userSpan = userTag.querySelector('span');
            userSpan.textContent = `${user.phone || authorization.userId || ''} (${user.nickname || '未知用户'})`;

            const userIdInput = modal.querySelector('#user-id');
            userIdInput.value = user.id || authorization.userId || '';

            // 显示用户标签
            userTag.style.display = 'flex';
            // 填充阶段选项
            const stageSelect = modal.querySelector('#stage-id');
            this.populateStageOptions(stageSelect);

            // 选择当前阶段
            for (let i = 0; i < stageSelect.options.length; i++) {
                if (parseInt(stageSelect.options[i].value) === authorization.stageId) {
                    stageSelect.selectedIndex = i;
                    break;
                }
            }

            // 处理日期格式
            let startTimeValue = '';
            let endTimeValue = '';

            if (authorization.startTime) {
                if (authorization.startTime.includes('T')) {
                    // ISO格式日期
                    startTimeValue = authorization.startTime.split('T')[0];
                } else {
                    // 尝试解析其他格式的日期
                    const startDate = new Date(authorization.startTime);
                    if (!isNaN(startDate.getTime())) {
                        startTimeValue = startDate.toISOString().split('T')[0];
                    }
                }
            }

            if (authorization.endTime) {
                if (authorization.endTime.includes('T')) {
                    // ISO格式日期
                    endTimeValue = authorization.endTime.split('T')[0];
                } else {
                    // 尝试解析其他格式的日期
                    const endDate = new Date(authorization.endTime);
                    if (!isNaN(endDate.getTime())) {
                        endTimeValue = endDate.toISOString().split('T')[0];
                    }
                }
            }

            // 填充日期
            modal.querySelector('#start-time').value = startTimeValue;
            modal.querySelector('#end-time').value = endTimeValue;
        }
        else {
            // 显示用户标签
            userTag.style.display = 'none';
            // 添加模式 - 设置默认值
            const stageSelect = modal.querySelector('#stage-id');
            this.populateStageOptions(stageSelect);

            const startTimeInput = modal.querySelector('#start-time');
            const endTimeInput = modal.querySelector('#end-time');
            startTimeInput.value = todayStr;
            endTimeInput.value = defaultEndTimeStr;
        }

        // 处理用户标签关闭
        const closeTag = userTag.querySelector('.close-tag');
        if (closeTag) {
            closeTag.addEventListener('click', (event) => {
                event.stopPropagation();
                userTag.style.display = 'none';
                const phoneInput = modal.querySelector('#phone');
                if (phoneInput) {
                    phoneInput.style.display = 'block';
                    phoneInput.setAttribute('required', 'required');
                }

                // 清除隐藏的用户ID字段
                if (userIdInput) {
                    userIdInput.value = '';
                }
            });
        }

        // 如果是编辑模式，确保手机号输入框有required属性
        if (mode === 'edit') {
            phoneInput.setAttribute('required', 'required');
        }

        // 设置用户搜索功能
        this.setupUserSearch(phoneInput, suggestionsDiv, userTag, userIdInput);

        // 设置关闭按钮
        this.setupCloseButtons(modal, closeBtn, cancelBtn);

        // 设置表单提交
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            if (mode === 'add') {
                this.addAuthorization();
            } else {
                this.updateAuthorization();
            }
        });

        // 显示模态框
        modal.style.display = 'block';
    }

    async loadStages() {
        try {
            const response = await this.app.authenticatedFetch('/api/course/getAllStage');
            const result = await response.json();
            
            if (result.code === 200) {
                this.stages = result.data || [];
            } else {
                console.error('获取阶段数据失败:', result.message);
                this.stages = [];
            }
        } catch (error) {
            console.error('加载阶段数据失败:', error);
            this.stages = [];
        }
    }

    async searchUsersByPhone(phone) {
        try {
            const response = await this.app.authenticatedFetch(`/api/web/user/search?phone=${encodeURIComponent(phone)}`);
            const result = await response.json();
            
            if (result.code === 200) {
                return result.data || [];
            } else {
                console.error('搜索用户失败:', result.message);
                return [];
            }
        } catch (error) {
            console.error('搜索用户失败:', error);
            return [];
        }
    }

    async addAuthorization() {
        const form = document.getElementById('authorization-form');
        const phoneInput = document.getElementById('phone');
        const formData = new FormData(form);
        
        // 获取用户ID（从隐藏字段）
        let userId = formData.get('userId');
        // 如果隐藏字段中没有userId，则尝试从已选择的用户中获取
        if (!userId && phoneInput.getAttribute('data-selected-user') === 'true') {
            const hiddenUserIdInput = document.getElementById('user-id');
            if (hiddenUserIdInput) {
                userId = hiddenUserIdInput.value;
            }
        }
        
        // 检查是否已选择用户（通过用户标签是否显示来判断）
        const userTag = document.querySelector('.user-tag');
        if (!userId && (!userTag || userTag.style.display === 'none')) {
            alert('请先选择用户');
            return;
        }
        
        // 获取开始时间和结束时间
        let startTime = formData.get('startTime');
        let endTime = formData.get('endTime');
        
        // 如果没有设置结束时间，则设置为开始时间+30天
        if (!endTime) {
            if (startTime) {
                // 基于开始时间加30天
                const startDate = new Date(startTime);
                const endDate = new Date(startDate);
                endDate.setDate(startDate.getDate() + 30);
                endTime = endDate.toISOString().split('T')[0];
            } else {
                // 如果没有开始时间，则基于今天加30天
                const today = new Date();
                const endDate = new Date(today);
                endDate.setDate(today.getDate() + 30);
                endTime = endDate.toISOString().split('T')[0];
            }
        }
        
        // 如果有开始时间，确保格式正确
        if (startTime) {
            startTime = startTime + 'T00:00:00';
        }
        
        // 结束时间设置为当天的最后一刻
        if (endTime) {
            endTime = endTime + 'T23:59:59';
        }
        
        const authorizationData = {
            userId: parseInt(userId),
            stageId: parseInt(formData.get('stageId')),
            startTime: startTime,
            endTime: endTime
        };
        
        try {
            const response = await this.app.authenticatedFetch('/api/web/authorization/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(authorizationData)
            });
            
            const result = await response.json();
            
            if (result.code === 200) {
                // 关闭模态框
                const modal = document.getElementById('authorization-modal');
                if (modal && modal.parentNode) {
                    modal.parentNode.removeChild(modal);
                }
                
                // 重新加载授权数据
                this.loadAuthorizations();
                
                alert('授权添加成功');
            } else {
                alert('添加失败: ' + result.message);
            }
        } catch (error) {
            console.error('添加授权失败:', error);
            alert('添加授权失败，请稍后重试');
        }
    }

    editAuthorization(id) {
        // 编辑授权
        this.showAuthorizationModal('edit', id);
    }

    async updateAuthorization() {
        const form = document.getElementById('authorization-form');
        const formData = new FormData(form);
        
        // 获取用户ID
        let userId = formData.get('userId');
        
        // 检查是否已选择用户（通过用户标签是否显示来判断）
        const userTag = document.querySelector('.user-tag');
        if (!userId && (!userTag || userTag.style.display === 'none')) {
            alert('请先选择用户');
            return;
        }
        
        const authorizationData = {
            id: parseInt(formData.get('id')),
            userId: parseInt(userId),
            stageId: parseInt(formData.get('stageId')),
            startTime: formData.get('startTime') ? formData.get('startTime') + 'T00:00:00' : null,
            endTime: formData.get('endTime') ? formData.get('endTime') + 'T23:59:59' : null
            // 不传递创建时间，让后端处理
        };
        
        try {
            const response = await this.app.authenticatedFetch('/api/web/authorization/update', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(authorizationData)
            });
            
            const result = await response.json();
            
            if (result.code === 200) {
                // 关闭模态框
                const modal = document.getElementById('authorization-modal');
                if (modal && modal.parentNode) {
                    modal.parentNode.removeChild(modal);
                }
                
                // 重新加载授权数据
                this.loadAuthorizations();
                
                alert('授权更新成功');
            } else {
                alert('更新失败: ' + result.message);
            }
        } catch (error) {
            console.error('更新授权失败:', error);
            alert('更新授权失败，请稍后重试');
        }
    }

    cancelAuthorization(id) {
        // 取消授权
        if (confirm('确定要取消这个授权吗？此操作会将授权的结束时间设置为昨天。')) {
            this.performCancelAuthorization(id);
        }
    }

    async performCancelAuthorization(id) {
        try {
            // 获取当前授权信息
            const response = await this.app.authenticatedFetch('/api/web/authorization/getAll');
            const result = await response.json();
            
            if (result.code !== 200) {
                alert('获取授权信息失败: ' + result.message);
                return;
            }
            
            const authorizations = result.data || [];
            const authorization = authorizations.find(auth => auth.id === id);
            
            if (!authorization) {
                alert('未找到指定的授权信息');
                return;
            }
            
            // 设置结束时间为昨天
            const yesterday = new Date();
            yesterday.setDate(yesterday.getDate() - 1);
            
            // 构造更新数据
            const updatedAuthorization = {
                id: authorization.id,
                userId: authorization.userId,
                stageId: authorization.stageId,
                startTime: authorization.startTime,
                endTime: yesterday.toISOString().split('T')[0] + 'T23:59:59' // 设置为昨天的最后一刻
            };
            
            // 发送更新请求
            const updateResponse = await this.app.authenticatedFetch('/api/web/authorization/update', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(updatedAuthorization)
            });
            
            const updateResult = await updateResponse.json();
            
            if (updateResult.code === 200) {
                // 更新成功，重新加载授权数据
                await this.loadAuthorizations();
                alert('授权已取消');
            } else {
                alert('取消授权失败: ' + updateResult.message);
            }
        } catch (error) {
            console.error('取消授权失败:', error);
            alert('取消授权失败，请稍后重试');
        }
    }

    deleteAuthorization(id) {
        // 删除授权
        if (confirm('确定要删除这个授权吗？此操作不可恢复！')) {
            this.performDeleteAuthorization(id);
        }
    }

    async performDeleteAuthorization(id) {
        try {
            const response = await this.app.authenticatedFetch(`/api/web/authorization/delete/${id}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            const result = await response.json();
            
            if (result.code === 200) {
                // 删除成功，重新加载授权数据
                await this.loadAuthorizations();
                alert('授权删除成功');
            } else {
                alert('删除失败: ' + result.message);
            }
        } catch (error) {
            console.error('删除授权失败:', error);
            alert('删除授权失败，请稍后重试');
        }
    }

    searchAuthorizations(keyword) {
        // 搜索授权
        console.log('Searching authorizations with keyword:', keyword);
    }
}